import { Component, ElementRef, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { NzTreeFlatDataSource, NzTreeFlattener } from 'ng-zorro-antd/tree-view';
import { Host, HostConfigService } from '../../../service/config.service';
import { FlatTreeControl } from '@angular/cdk/tree';
import { SelectionModel } from '@angular/cdk/collections';

@Component({
  selector: 'app-host-tree',
  templateUrl: './host-tree.component.html',
  styleUrls: ['./host-tree.component.css']
})
export class HostTreeComponent implements OnInit {

  constructor(private elementRef: ElementRef, private hostCfg: HostConfigService) { }

  @Input() styleClass: string;
  @Output() onClick: EventEmitter<any> = new EventEmitter();
  @Output() onDblClick: EventEmitter<any> = new EventEmitter();
  @Output() onContextMenu: EventEmitter<any> = new EventEmitter();
  ngOnInit(): void {
    this.showTreeView();
    this.hostCfg.configChange$.subscribe((data) => {
      this.showTreeView();
    })
  }
  isTreeViewOpened = false;
  selectedHost: Host;
  private transformer = (host: Host, level: number) => {
    return {
      expandable: !!host.children && host.children.length > 0,
      name: host.title,
      level: level,
      host: host
    };
  };
  treeFlattener = new NzTreeFlattener(
    this.transformer,
    node => node.level,
    node => node.expandable,
    node => node.children
  );
  treeControl = new FlatTreeControl<any>(
    node => node.level,
    node => node.expandable
  );
  dataSource = new NzTreeFlatDataSource(this.treeControl, this.treeFlattener);
  selectListSelection = new SelectionModel<any>(true);
  showTreeView() {
    this.dataSource.setData([this.hostCfg.getHostConfig()]);
    this.treeControl.expandAll();
  }
  clickTreeNode(node) {
    let nodes = this.dataSource._flattenedData.value;
    this.selectedHost = node.host;
    for (let i = 0; i < nodes.length; i++) {
      if (nodes[i] == node) {
        this.selectListSelection.select(nodes[i]);
      }
      else {
        this.selectListSelection.deselect(nodes[i]);
      }
    }
    this.onClick.emit(this.selectedHost);
  }
  dblClickTreeNode(_e, node) {
    this.onDblClick.emit(node.host);
  }
  rightClickTreeNode(e, node) {
    this.clickTreeNode(node);
    this.onContextMenu.emit({ event: e, host: node.host });
  }
  hasChild = (_: number, node: any) => node.host.children && node.host.children.length > 0;
  isHostWithChild = (_: number, node: any) => this.hostCfg.isHost(node.host) && node.host.children && node.host.children.length > 0;
  isForward = (_: number, node: any) => this.hostCfg.isForward(node.host);
  isGroup = (_: number, node: any) => this.hostCfg.isGroup(node.host);
  isHostSelected = () => { return this.hostCfg.isNotForward(this.selectedHost); }
  isForwardSelected = () => { return this.hostCfg.isForward(this.selectedHost); }
}
